'use client';

import * as React from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import AnimatedBackground from '../components/AnimatedBackground';
import { useAuth } from '@/lib/context/auth';
import Link from 'next/link';
import { useEffect } from 'react';

interface LoginError {
  field: string;
  message: string;
}

// 密码验证规则
const PASSWORD_RULES = {
  minLength: 6,
  maxLength: 20,
  // 不允许的特殊字符
  invalidChars: /[<>"']/g,
  // 允许的特殊字符
  validSpecialChars: /^[A-Za-z0-9!@#$%^&*()_+\-=[\]{};:,./\\|~`]+$/,
};

export default function LoginPage() {
  const router = useRouter();
  const { login } = useAuth();
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [rememberMe, setRememberMe] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const [error, setError] = React.useState<LoginError | null>(null);

  // 监听用户状态变化
  useEffect(() => {
    if (router.pathname === '/main') {
      router.replace('/main');
    }
  }, [router]);

  // 验证用户名
  const validateUsername = (value: string): boolean => {
    if (!value.trim()) {
      setError({ field: 'username', message: '请输入用户名' });
      return false;
    }
    if (value.length < 2) {
      setError({ field: 'username', message: '用户名至少需要2个字符' });
      return false;
    }
    if (value.length > 50) {
      setError({ field: 'username', message: '用户名不能超过50个字符' });
      return false;
    }
    return true;
  };

  // 验证密码
  const validatePassword = (value: string): boolean => {
    if (!value) {
      setError({ field: 'password', message: '请输入密码' });
      return false;
    }
    if (value.length < PASSWORD_RULES.minLength) {
      setError({ 
        field: 'password', 
        message: `密码长度不能少于${PASSWORD_RULES.minLength}个字符` 
      });
      return false;
    }
    if (value.length > PASSWORD_RULES.maxLength) {
      setError({ 
        field: 'password', 
        message: `密码长度不能超过${PASSWORD_RULES.maxLength}个字符` 
      });
      return false;
    }
    if (PASSWORD_RULES.invalidChars.test(value)) {
      setError({ 
        field: 'password', 
        message: '密码包含不允许的特殊字符' 
      });
      return false;
    }
    if (!PASSWORD_RULES.validSpecialChars.test(value)) {
      setError({ 
        field: 'password', 
        message: '密码只能包含字母、数字和允许的特殊字符' 
      });
      return false;
    }
    return true;
  };

  // 表单验证
  const validateForm = (): boolean => {
    return validateUsername(username) && validatePassword(password);
  };

  // 处理密码输入变化
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newPassword = e.target.value;
    // 实时移除不允许的字符
    const sanitizedPassword = newPassword.replace(PASSWORD_RULES.invalidChars, '');
    setPassword(sanitizedPassword);
    setError(null);
  };

  // 处理用户名输入变化
  const handleUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setUsername(e.target.value);
    setError(null);
  };

  // 处理登录
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    // 表单验证
    if (!validateForm()) return;

    try {
      setIsLoading(true);
      const user = await login(username, password);
      
      if (user) {
        // 登录成功，直接跳转到 main 页面
        router.replace('/main');
      }
    } catch (err) {
      console.error('Login error:', err);
      setError({
        field: 'submit',
        message: err instanceof Error ? err.message : '登录失败，请稍后重试',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 relative overflow-hidden">
      <AnimatedBackground />
      <div className="max-w-md w-full space-y-8 p-8 rounded-lg shadow-lg relative z-10 backdrop-blur-sm 
        bg-gradient-to-br from-purple-500/90 via-indigo-500/90 to-purple-600/90 
        dark:from-purple-900/90 dark:via-indigo-900/90 dark:to-purple-950/90">
        {/* Logo */}
        <div className="flex flex-col items-center">
          <Image
            src="/LawyerAI-Logo.png"
            alt="LawyerAI Logo"
            width={120}
            height={120}
            className="mb-4 rounded-full bg-white/10 p-2 backdrop-blur-sm"
            priority
          />
          <p className="mt-2 text-sm text-gray-100">
            欢迎使用"精英律师"的AI助手
          </p>
        </div>

        {/* 登录表单 */}
        <form className="mt-8 space-y-6" onSubmit={handleLogin}>
          <div className="space-y-4">
            {/* 用户名输入 */}
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-white">
                用户名
              </label>
              <div className="mt-1">
                <input
                  id="username"
                  name="username"
                  type="text"
                  autoComplete="username"
                  required
                  value={username}
                  onChange={handleUsernameChange}
                  disabled={isLoading}
                  className={`appearance-none block w-full px-3 py-2 border ${
                    error?.field === 'username' ? 'border-red-300' : 'border-blue-300'
                  } rounded-md shadow-sm placeholder-gray-400 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                    bg-black/30 text-white backdrop-blur-sm`}
                  placeholder="请输入用户名"
                />
              </div>
              {error?.field === 'username' && (
                <p className="mt-1 text-sm text-red-300">{error.message}</p>
              )}
            </div>

            {/* 密码输入 */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-white">
                密码
              </label>
              <div className="mt-1">
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required
                  value={password}
                  onChange={handlePasswordChange}
                  disabled={isLoading}
                  className={`appearance-none block w-full px-3 py-2 border ${
                    error?.field === 'password' ? 'border-red-300' : 'border-blue-300'
                  } rounded-md shadow-sm placeholder-gray-400
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                    bg-black/30 text-white backdrop-blur-sm`}
                  placeholder="请输入密码"
                />
              </div>
              {error?.field === 'password' && (
                <p className="mt-1 text-sm text-red-300">{error.message}</p>
              )}
            </div>
          </div>

          {/* 记住我和忘记密码 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <input
                id="remember-me"
                name="remember-me"
                type="checkbox"
                checked={rememberMe}
                onChange={(e) => setRememberMe(e.target.checked)}
                disabled={isLoading}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
              />
              <label htmlFor="remember-me" className="ml-2 block text-sm text-gray-100">
                记住我
              </label>
            </div>

            <div className="text-sm">
              <Link
                href="/reset-password"
                className="font-medium text-blue-300 hover:text-blue-200"
              >
                忘记密码？
              </Link>
            </div>
          </div>

          {/* 登录按钮 */}
          <div>
            <button
              type="submit"
              disabled={isLoading}
              className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? (
                <div className="w-5 h-5 border-t-2 border-white rounded-full animate-spin"></div>
              ) : (
                '登录'
              )}
            </button>
          </div>

          {/* 全局错误信息 */}
          {error?.field === 'submit' && (
            <div className="text-center text-red-300 text-sm">{error.message}</div>
          )}

          {/* 注册链接 */}
          <div className="text-center">
            <span className="text-gray-200">还没有账号？</span>
            <Link
              href="/register"
              className="ml-1 font-medium text-blue-300 hover:text-blue-200"
            >
              立即注册
            </Link>
          </div>
        </form>
      </div>
    </div>
  );
}
